import { cloudSocketURL } from "@/configs/jy";
import { handleEquipReg } from "./utils/handleEquipReg";
import { handleModbusReg } from "./utils/handleModbusReg";
import { handleLoraParamsReg } from "./utils/handleLoraParamsReg";
import { handleJsonMsg } from "./utils/handleJsonMsg";
import { SocketData, SendInfoType, ModbusReg, JsonMsg, LoraCommParamsSocketData, LoraWorkParamsSocketData, LoraTimeParamsSocketData } from "./types/SocketData";

let count = 0;
export let isRegistered = false; // 是否注册成功
let equipSocket: WebSocket | null = null; // socket实例
let onMessageFn: ((socketData: SocketData) => any) | null = null;
export const onMessage = (callback: (socketData: SocketData) => any) => (onMessageFn = callback);
// 发送消息
export const equipSocketSend = ({ infotype, info }: { infotype: SendInfoType; info?: string | any[] | { [propName: string]: any } }) => {
    let token = localStorage.getItem("access_token") || "";
    if (equipSocket?.readyState == equipSocket?.OPEN) {
        equipSocket!.send(JSON.stringify({ infotype, info, token }));
    } else {
        equipSocketInit();
    }
};
// 初始化socket
export const equipSocketInit = () => {
    isRegistered = false;
    equipSocketClose();
    equipSocket = new WebSocket(cloudSocketURL);
    equipSocket.onopen = () => {
        equipSocketSend({ infotype: "register", info: "" }); // 注册
    };
    equipSocket.onmessage = ({ data }) => {
        // try {
        count = 0;
        let socketData = JSON.parse(data) as SocketData;
        switch (socketData.infotype) {
            case "untoken":
                break;
            case "register":
                socketData.info == "OK" && (isRegistered = true);
                break;
            case "damreadall":
                // (socketData.info as unknown as Equip.EquipRegData[]).forEach((v) => updateEquipRegData({ equipData: v }));
                break;
            case "damread":
            case "EquipInfoNow":
                handleEquipReg(socketData.info as Equip.EquipRegData);
                break;
            case "ModbusReg":
                handleModbusReg(socketData.info as ModbusReg);
                break;
            case "CRFParamMaster":
            case "CRFLoraParam":
                handleLoraParamsReg(socketData as LoraCommParamsSocketData);
                break;
            case "CRFConfigKTCV2":
                handleLoraParamsReg(socketData as LoraWorkParamsSocketData);
                break;
            case "CRFLoraTiming":
                handleLoraParamsReg(socketData as LoraTimeParamsSocketData);
                break;
            case "JsonMsg":
                handleJsonMsg(socketData.info as JsonMsg);
                break;
        }
        onMessageFn && onMessageFn(socketData);
        // } catch (err: any) {
        //     console.error("EquipSocket onmessage Error: " + err);
        // }
    };
};
// 心跳机制
export const equipSocketPingPong = () => {
    try {
        count++;
        if (count >= 120) {
            // 2分钟ws未收到消息，则会重连
            count = 0;
            equipSocketInit();
        }
    } catch (err: any) {
        console.error("EquipSocket Error: " + err);
    }
};
// 关闭socket
export const equipSocketClose = () => {
    if (equipSocket) {
        equipSocket.close();
        isRegistered = false;
    }
};
